package top.z.work.module.system.mapper;

import com.mybatisflex.core.BaseMapper;
import com.mybatisflex.core.query.DistinctQueryColumn;
import com.mybatisflex.core.query.QueryChain;
import com.mybatisflex.core.query.QueryWrapper;
import top.z.work.module.system.entity.SystemRoleRoute;
import top.z.work.module.system.entity.SystemRoute;
import top.z.work.module.system.entity.SystemUser;
import top.z.work.module.system.entity.table.SystemRoleRouteTableDef;
import top.z.work.module.system.entity.table.SystemRouteTableDef;
import top.z.work.module.system.entity.table.SystemUserRoleTableDef;
import top.z.work.module.system.entity.table.SystemUserTableDef;

import java.util.List;

/**
 * 角色路由Mapper
 *
 * @author zaoangod
 * @since 2024-06-24 17:35:45
 */
public interface SystemRoleRouteMapper extends BaseMapper<SystemRoleRoute> {

    /**
     * 查询用户拥有的路由列表
     *
     * @param userId 用户ID
     * @return 路由列表
     */
    default List<SystemRoute> selectUserMenuList(Long userId) {
        /*
         * select distinct c.* from system_role_route a
         *      left join system_user_role b on a.role_id = b.role_id
         *      left join system_route c on a.route_id = c.identity
         * where b.user_id = ?
         */
        QueryWrapper query = new QueryWrapper();
        query.select(new DistinctQueryColumn(SystemRouteTableDef.SYSTEM_ROUTE.ALL_COLUMNS))
                .from(SystemRoleRouteTableDef.SYSTEM_ROLE_ROUTE)
                .leftJoin(SystemUserRoleTableDef.SYSTEM_USER_ROLE).on(SystemRoleRouteTableDef.SYSTEM_ROLE_ROUTE.ROLE_ID.eq(SystemUserRoleTableDef.SYSTEM_USER_ROLE.ROLE_ID))
                .leftJoin(SystemRouteTableDef.SYSTEM_ROUTE).on(SystemRoleRouteTableDef.SYSTEM_ROLE_ROUTE.ROUTE_ID.eq(SystemRouteTableDef.SYSTEM_ROUTE.IDENTITY))
                .where(SystemUserRoleTableDef.SYSTEM_USER_ROLE.USER_ID.eq(userId));
        return this.selectListByQueryAs(query, SystemRoute.class);
    }

    /**
     * 根据角色ID查询用户列表
     *
     * @param roleId 角色ID
     * @return 用户列表
     */
    default List<SystemUser> selectRoleRelateUser(Long roleId) {
        /*
         * select b.* from system_user_role a
         * left join system_user b on a.user_id = b.identity
         * where a.role_id = ?
         */
        QueryWrapper query = QueryChain.create()
                .select(SystemUserTableDef.SYSTEM_USER.ALL_COLUMNS)
                .from(SystemUserRoleTableDef.SYSTEM_USER_ROLE)
                .leftJoin(SystemUserTableDef.SYSTEM_USER).on(SystemUserRoleTableDef.SYSTEM_USER_ROLE.USER_ID.eq(SystemUserTableDef.SYSTEM_USER.IDENTITY))
                .where(SystemUserRoleTableDef.SYSTEM_USER_ROLE.ROLE_ID.eq(roleId));
        return this.selectListByQueryAs(query, SystemUser.class);
    }

}
